package com.kwan.xframe.util;

import java.util.Arrays;


/**
 * byte    8位 1个字节
 * boolen  8位 1个字节
 * short  16位 2个字节
 * char   16位 2个字节
 * int    32位 4个字节
 * float  32位 4个字节
 * double 64位 8个字节
 * long   64位 8个字节
 */

public class ByteArrayUtil {

	/**
	 * 拆分 byte[]
	 * @param src
	 * @param begin
	 * @param count
	 * @return
	 */

	public static byte[] subBytes(byte[] src, int begin, int count) {
		byte[] bs = new byte[count];
		System.arraycopy(src, begin, bs, 0, count);
		return bs;
	}


	public static short getShort(byte[] b, int index) {
		return (short) (((b[index + 1] << 8) | b[index] & 0xff));
	}


	//将整数按照小端存放，低字节出访低位
	public static byte[] short2bytesL(short n) {
		byte[] b = new byte[2];
		b[0] = (byte) (n & 0xff);
		b[1] = (byte) (n >> 8 & 0xff);
		return b;
	}

	/**
	 * 将int转为大端，低字节存储高位
	 *
	 * @param n int
	 * @return byte[]
	 */
	public static byte[] short2bytesH(short n) {
		byte[] b = new byte[2];
		b[0] = (byte) (n >> 8 & 0xff);
		b[1] = (byte) (n & 0xff);
		return b;
	}


	/**
	 * int 转 byte 大端
	 * 高位在前，低位在后
 	 */

	public static byte[] int2bytes(int num) {
		byte[] result = new byte[4];
		result[0] = (byte) ((num >>> 24) & 0xff);
		result[1] = (byte) ((num >>> 16) & 0xff);
		result[2] = (byte) ((num >>> 8) & 0xff);
		result[3] = (byte) ((num >>> 0) & 0xff);
		return result;
	}

	/**
	 * int 转 byte 小端
	 * 高位在后，低位在前
	 */

	public static byte[] int2bytesL(int num) {
		byte[] result = new byte[4];
		result[3] = (byte) ((num >>> 24) & 0xff);
		result[2] = (byte) ((num >>> 16) & 0xff);
		result[1] = (byte) ((num >>> 8) & 0xff);
		result[0] = (byte) ((num >>> 0) & 0xff);
		return result;
	}

	/**
	 * byte[] 转int 大端 高位在前，低位在后
	 * @param bytes
	 * @return
	 */
	public static int bytes2int(byte[] bytes) {
		int result = 0;
		if (bytes.length == 4) {
			int a = (bytes[0] & 0xff) << 24;
			int b = (bytes[1] & 0xff) << 16;
			int c = (bytes[2] & 0xff) << 8;
			int d = (bytes[3] & 0xff);
			result = a | b | c | d;
		}
		return result;
	}


	/**
	 * 合并 byte[]
	 * @param first
	 * @param rest
	 * @return 合并后的 byte[]
	 */

	public static byte[] concatAll(byte[] first, byte[]... rest) {
		int totalLength = first.length;
		for (byte[] array : rest) {
			totalLength += array.length;
		}
		byte[] result = Arrays.copyOf(first, totalLength);

		int offset = first.length;
		for (byte[] array : rest) {
			System.arraycopy(array, 0, result, offset, array.length);
			offset += array.length;
		}
		return result;
	}

	@SafeVarargs
	public static <T> T[] concatAll(T[] first, T[]... rest) {

		int totalLength = first.length;
		for (T[] array : rest) {
			totalLength += array.length;
		}
		T[] result =
				Arrays.copyOf(first, totalLength);
		int offset = first.length;
		for (T[] array : rest) {
			System.arraycopy(array, 0, result, offset, array.length);
			offset += array.length;
		}
		return result;
	}

}
